package com.elock.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.dao.impl.NativeDao;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.JsonUtils;
import com.elock.entity.ElectronicFence;
import com.elock.service.ElectronicFenceService;
import com.elock.service.SaleOrgBaseService;
import com.elock.util.PointUtil;

/**
 * Controller - 电子围栏
 * 
 * @author 仁德
 */
@Controller("electronicFenceController")
@RequestMapping("/electronic_fence")
public class ElectronicFenceController extends BaseController {

	@Resource(name = "electronicFenceServiceImpl")
	private ElectronicFenceService electronicFenceService;
	@Resource(name = "nativeDao")
	private NativeDao nativeDao;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(ModelMap model) {

		return "/electronic_fence/list_tb";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {

		return "/electronic_fence/list";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg list_data(String name, Integer type, Long saleOrgId,
			String startTime, String endTime, Pageable pageable, ModelMap model) {

//		List<Filter> filters = new ArrayList<Filter>();
//		if (!ConvertUtil.isEmpty(name)) {
//			filters.add(Filter.like("name", "%" + name + "%"));
//		}
//		if (type != null) {
//			filters.add(Filter.eq("type", type));
//		}
//		Page<ElectronicFence> page = electronicFenceService.findPage(filters,
//				null, pageable);
		Page<Map<String, Object>> page = electronicFenceService.findPage(name,
				type,
				saleOrgId,
				startTime,
				endTime,
				pageable);
		String jsonPage = JsonUtils.toJson(page);

		return success(jsonPage);
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap model) {
		model.addAttribute("saleOrg", saleOrgBaseService.getCurrentSaleOrg());
		return "/electronic_fence/add";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public @ResponseBody ResultMsg save(ElectronicFence electronicFence,
			Long[] terminalId, Long saleOrgId) {

		if (ConvertUtil.isEmpty(electronicFence.getName())) {
			return error("请填写围栏名称");
		}
		// 校验关联数量
		if (terminalId != null) {
			String check = electronicFenceService.check(terminalId,
					electronicFence.getId());
			if (!check.equals("") && check != null && check.length() > 0) {
				return error(check);
			}
		}

		electronicFenceService.saveUpdate(electronicFence, terminalId, saleOrgId);

		return success().addObjX(electronicFence.getId());
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model) {

		ElectronicFence electronicFence = electronicFenceService.find(id);
		model.addAttribute("electronicFence", electronicFence);

		/** 机构 */
		String sql = "SELECT so.`id`,so.`name` FROM electronic_fence ef , electronic_fence_sale_org efso , "
				+ "sale_org so WHERE ef.id = efso.electronic_fence_id AND  efso.sale_org_id = so.id AND ef.id = ?";
		Map<String, Object> map = nativeDao.findSingleMap(sql, new Object[] { id });
		model.addAttribute("salesOrg", map);

		/** 终端 */
		String sql_t = "SELECT t.terminal_num,t.id,t.sim,t.remark,t.terminal_name,sdt.value type_value,sdm.value model_value FROM terminal t left join terminal_electronic_fence tef on t.id = tef.terminal_id left join system_dict sdt on t.type=sdt.id left join system_dict sdm on t.model=sdm.id WHERE tef.electronic_fence_id = ?";
		List<Map<String, Object>> maps = nativeDao.findListMap(sql_t,
				new Object[] { id },
				0);
		String jsonStr = JsonUtils.toJson(maps);
		model.addAttribute("jsonStr", jsonStr);

		return "/electronic_fence/edit";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody ResultMsg update(ElectronicFence electronicFence,
			Long[] terminalId, Long saleOrgId) {

		if (ConvertUtil.isEmpty(electronicFence.getName())) {
			return error("请填写围栏名称");
		}

		// 校验关联数量
		if (terminalId != null) {
			String check = electronicFenceService.check(terminalId,
					electronicFence.getId());
			if (!check.equals("") && check != null && check.length() > 0) {
				return error(check);
			}
		}

		electronicFenceService.saveUpdate(electronicFence, terminalId, saleOrgId);

		return success();
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody ResultMsg delete(Long[] ids) {

		electronicFenceService.delete(ids);
		return success();

	}

	/**
	 * 根据钥匙id获取电子围栏
	 */
	@RequestMapping(value = "/getElectronicFence", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getElectronicFence(Long terminalId) {

		String sql = "select tef.*,ef.name electronic_fence_name,ef.type,ef.radius,ef.points,ef.judgment_rule"
				+ " from terminal_electronic_fence tef,electronic_fence ef"
				+ " where tef.electronic_fence_id=ef.id and tef.terminal_id = ?";
		List<Map<String, Object>> list = electronicFenceService.getDaoCenter()
				.getNativeDao()
				.findListMap(sql, new Object[] { terminalId }, 0);

		return success().addObjX(list);
	}

	/**
	 * 获取点(纬度、经度)方圆3公里内的电子围栏
	 */
	@RequestMapping(value = "/getRangeFences", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getRangeFences(Double latitude, Double longitude,
			Double distance) {

		if (distance == null) {
			distance = 3000D;
		}
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Integer pageNumber = 1;
		Pageable pageable = new Pageable(pageNumber, 300);

		while (true) {
			Page<Map<String, Object>> page = electronicFenceService.findPage(null,
					null,
					null,
					null,
					null,
					pageable);
			List<Map<String, Object>> fences = page.getContent();
			for (Map<String, Object> map : fences) {
				int type = Integer.parseInt(map.get("type").toString());
				double lat = 0;
				double lng = 0;
				if (type == 0) {
					lat = Double.parseDouble(map.get("latitude").toString());
					lng = Double.parseDouble(map.get("longitude").toString());
				}
				else {
					String points = map.get("points").toString();
					points = points.substring(0,
							points.length() > 30 ? 30 : points.length());
					String[] pointArr = points.split(",");
					lat = Double.parseDouble(pointArr[0].toString());
					lng = Double.parseDouble(pointArr[1].toString());
				}
				double calcDistance = PointUtil.getDistance(latitude,
						longitude,
						lat,
						lng);
				if (calcDistance < distance) {
					list.add(map);
				}
			}
			if (fences.size() < 300) {
				break;
			}
			pageNumber++;
			pageable.setPageNumber(pageNumber);
		}

		return success().addObjX(list);
	}

	/**
	 * GPS84坐标转换成百度坐标
	 */
	@RequestMapping(value = "/gps84_to_bd", method = RequestMethod.POST)
	public @ResponseBody ResultMsg gps84_to_bd(Double latitude, Double longitude) {

		Map<String, Double> point = new HashMap<String, Double>();
		double[] points = PointUtil.gps84_to_bd(latitude, longitude);
		point.put("latitude", points[0]);
		point.put("longitude", points[1]);

		return success().addObjX(point);
	}
}
